//
//  PicturePickerController.swift
//  照片选择
//
//  Created by apple on 15/12/18.
//  Copyright © 2015年 idcast. All rights reserved.
//

import UIKit
///可重用cell
private let picturePickerCellID = "picturePickerCellID"
///最大照片选择数量
private let PicturePickerMaxCount = 4

class PicturePickerController: UICollectionViewController {
    
    ///配图数组
    lazy var pictursCount = [UIImage]()
    ///当前用户选中的照片
    private var selectedIndex = 0
    
    ///构造函数
    init() {
    
        super.init(collectionViewLayout: PicturePickerLayout())
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView?.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
        //可重用cell
        self.collectionView!.registerClass(PicturePickerCell.self, forCellWithReuseIdentifier: picturePickerCellID)

    }

}

//MARK: 照片选择器布局  类中类

private class PicturePickerLayout: UICollectionViewFlowLayout {

    private override func prepareLayout() {
        super.prepareLayout()
        
        let count:CGFloat = 4
        
        let margin = UIScreen.mainScreen().scale * 4
        
        let w = (collectionView!.bounds.width - (count + 1) * margin) / count
        
        itemSize = CGSize(width: w, height: w)
        
        sectionInset  = UIEdgeInsetsMake(margin, margin, 0, margin)
        minimumInteritemSpacing = margin
        minimumLineSpacing = margin
    }
    
}



// MARK: UICollectionViewDataSource   数据源方法
extension PicturePickerController {
    
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return pictursCount.count + (pictursCount.count == PicturePickerMaxCount ? 0 : 1)
        
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(picturePickerCellID, forIndexPath: indexPath) as! PicturePickerCell
        
        cell.backgroundColor = UIColor.redColor()
 
        cell.image = (indexPath.item < pictursCount.count) ? pictursCount[indexPath.item] : nil
        //设置代理 
        cell.pictureDelegate = self
        
        return cell
    }
}

//MARK:PicturePickerCellDelegate
extension PicturePickerController: PicturePickerCellDelegate {

    @objc private func picturePickerCellDidAdd(cell: PicturePickerCell) {

        //判断是否支持访问照片库
        if !UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary){
        
            print("不允许访问照片库")
            return
        }
        //记录当前用户选中的照片的索引
        selectedIndex = collectionView?.indexPathForCell(cell)?.item ?? 0
        
        //显示照片选择器
        let picker = UIImagePickerController()
        
        //设置代理
        picker.delegate = self
        
        presentViewController(picker, animated: true, completion: nil)
        
    }
    @objc private func picturePickerCellDidRemove(cell: PicturePickerCell) {
//        print("删除照片")
        //1 获取照片索引
        let indexPath = collectionView!.indexPathForCell(cell)!
        //2 判断索引是否超出上限
        if indexPath.item >= pictursCount.count {
        
            return
        }
        //3 删除数据
        pictursCount.removeAtIndex(indexPath.item)
        
        //4 动画刷新试图
//        collectionView?.deleteItemsAtIndexPaths([indexPath])
        collectionView?.reloadData()
    }
}

/// 照片选择完成
///
/// - parameter picker: 照片选择控制器
/// - parameter info:   info 字典
/// - 提示：一旦实现代理方法，必须自己 dismiss
/// - picker.allowsEditing = true
/// - 适合用于`头像`选择
/// - UIImagePickerControllerEditedImage
/**
如果使用 cocos2dx 开发一个`空白的模板`游戏，内存占用 70M，iOS UI的空白应用程序，大概 19M

一般应用程序，内存在 100M 左右都是能够接受的！再高就需要注意！
*/

extension PicturePickerController: UINavigationControllerDelegate,UIImagePickerControllerDelegate {

    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        
        print(info)
        
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        
    
        //将图像添加到数组
        //判断当前选中的索引是否超出数组上线
        if selectedIndex >= pictursCount.count {
        
            pictursCount.append(image)
        }else {
        
            pictursCount[selectedIndex] = image
        }
        
        collectionView?.reloadData()

        //需要自己dismiss
        dismissViewControllerAnimated(true, completion: nil)
    }
}
///设置PicturePickerCellDelegate 代理
@objc
private protocol PicturePickerCellDelegate: NSObjectProtocol {

    ///添加按钮
    optional func picturePickerCellDidAdd(cell: PicturePickerCell)
    
    ///删除按钮
    optional func picturePickerCellDidRemove(cell: PicturePickerCell)
    
}

/// 照片选择cell
private class PicturePickerCell: UICollectionViewCell {
    
    ///照片图像
    private var image: UIImage? {
    
        didSet{
        
            addButton.setImage(image ?? UIImage(named: "compose_pic_add"), forState: .Normal)
            
            //隐藏删除按钮
            removeButton.hidden = (image == nil)
        }
    }
    
    ///照片选择代理
    weak var pictureDelegate: PicturePickerCellDelegate?
    
    
    ///MARK: 监听方法
    @objc func addPicture() {
    
        pictureDelegate?.picturePickerCellDidAdd?(self)
    }
    
    @objc func removePicture() {
    
        pictureDelegate?.picturePickerCellDidRemove?(self)
    }
    
    ///构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    ///设置控件
    private func setupUI() {
    
        ///1 添加控件
        contentView.addSubview(addButton)
        contentView.addSubview(removeButton)
        ///2 设置布局
        addButton.frame = bounds
        removeButton.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(contentView.snp_top)
            make.right.equalTo(contentView.snp_right)
        }
        ///监听方法
        addButton.addTarget(self, action: "addPicture", forControlEvents: .TouchUpInside)
        removeButton.addTarget(self, action: "removePicture", forControlEvents: .TouchUpInside)
        
        ///设置填充模式
        addButton.imageView?.contentMode = .ScaleAspectFill
        
    }
    
    //懒加载控件
    //添加按钮
    private lazy var addButton: UIButton = UIButton(imageName: "compose_pic_add", backImageName: nil)
    //删除按钮
    private lazy var removeButton: UIButton = UIButton(imageName: "compose_photo_close", backImageName: nil)
}
